package com.hbzhit.modules.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbzhit.common.utils.Constant;
import com.hbzhit.common.utils.ShiroUtils;
import com.hbzhit.modules.sys.dao.SysRoleMenuDao;
import com.hbzhit.modules.sys.entity.SysRoleMenuEntity;
import com.hbzhit.modules.sys.service.SysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;



/**
 * 角色与菜单对应关系
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuDao, SysRoleMenuEntity> implements SysRoleMenuService {

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
		//删除角色与菜单关系
        deleteBatch(new Long[]{roleId});

		if(CollUtil.isEmpty(menuIdList)){
			return;
		}

		//保存角色与菜单关系
        List<SysRoleMenuEntity> list = new ArrayList<>();
		for(Long menuId : menuIdList) {
			SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
			sysRoleMenuEntity.setMenuId(menuId);
			sysRoleMenuEntity.setRoleId(roleId);
			list.add(sysRoleMenuEntity);
		}
        if (CollectionUtil.isNotEmpty(list)) {
            this.saveBatch(list);
        }
	}

	@Override
	public List<Long> queryMenuIdList(Long roleId) {
		return baseMapper.queryMenuIdList(roleId);
	}

	@Override
	public List<Long> queryPermUserIdList(String[] perms) {
		Long orgId = ShiroUtils.getUser().getOrgId();
		List<Long> userIdList = baseMapper.queryPermUserIdList(new QueryWrapper<>()
				.in(perms != null && perms.length > 0, "m.perms", Arrays.asList(perms))
				.eq(orgId != null, "su.org_id", orgId)
		);
		if (userIdList == null) {
			userIdList = new ArrayList<>();
		}
		userIdList.add(Constant.SUPER_ADMIN);
		return userIdList;
	}

	@Override
	public void deleteBatch(Long[] roleIds){
		this.remove(new LambdaQueryWrapper<SysRoleMenuEntity>().in(SysRoleMenuEntity::getRoleId, Arrays.asList(roleIds)));
	}

}
